<template>
    <div>
        <!--查询条件start --111s-->
        <el-form :inline="true"
                 :model="query"
                 class="query-form"
                 size="small">
            <el-form-item>
                <el-button type="primary"
                           icon="el-icon-edit"
                           @click.native="showDialogAddOrEdit(null,null)">添加
                </el-button>
            </el-form-item>

            <el-form-item class="query-form-item">
                <el-input v-model="query.categoryname"
                          placeholder="请输入分类名称"
                          prefix-icon="el-icon-search"
                          @keyup.enter.native="onSubmit"
                          clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"
                           icon="el-icon-refresh"
                           @click="onRest"></el-button>
                <el-button type="primary"
                           icon="el-icon-search"
                           @click="onSubmit">查询</el-button>
            </el-form-item>

        </el-form>
        <!--查询条件end-->
        <!--列表start --->
        <el-table ref="multipleTable"
                  v-loading="loading"
                  :data="list"
                  :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
                  @selection-change="handleSelectionChange"
                  border>
            <el-table-column type="selection"  width="50"  fixed />
            <el-table-column label="ID"  prop="topcategoryid"  width="80"  align="center" />
            <el-table-column label="排序"  prop="topcategorysort"  width="80" align="center" />
            <el-table-column label="分类图"  prop="topcategorypic"  align="center" width="180">
                <template slot-scope="scope">
                    <el-popover v-if="scope.row.topcategorypic" placement="right"  trigger="hover">
                        <img :src="scope.row.topcategorypic"  style="width:400px;border-radius:3px;">
                        <img slot="reference" :src="scope.row.topcategorypic" style="max-height: 80px;max-width: 50px;border-radius:5px;">
                    </el-popover>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="一级分类"  with="300"  prop="topcategoryname"  align="center">
            </el-table-column>
            <el-table-column label="商品属性模板名称"  with="300" align="center">
                <template slot-scope="scope">
                    <span>{{scope.row.attributesname || "暂无模板"}}</span>
                </template>
            </el-table-column>
            <el-table-column label="添加时间"  with="200" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time"
                       v-if="scope.row.topcategorytime!=null"></i>
                    <span v-if="scope.row.topcategorytime!=null">{{ scope.row.topcategorytime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                    <span v-else>无</span>
                </template>
            </el-table-column>

            <el-table-column label="操作"  align="center" fixed="right" width="300">
                <template slot-scope="scope">
                    <el-button type="primary"  size="mini"  @click.native="toRelateTemplatePage(scope.row.topcategoryid,scope.row.attributesid)">商品属性模板关联</el-button>
                    <el-button type="primary"  size="mini"  @click.native="detailForm(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger"  size="mini"  @click.native="handleDel(scope.row.topcategoryid)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表end --222e-->

        <!--全选删除start-->
        <div class="left-container">
            <el-button type="danger"  size="small"  @click="delGroup()">删除已选</el-button>
            <transition name="el-fade-in-linear">
                <el-button size="small"  @click="toggleSelection()" v-show="cancelToggle">取消选择</el-button>
            </transition>
        </div>
        <!--全选删除end-->

        <!--分页模块start-->
        <el-pagination class="pagination-container"
                       background
                       :page-size="query.pageSize"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       layout="total,sizes,prev, pager, next, jumper"
                       :current-page="query.currentPage"
                       :page-sizes="[5,10, 20, 30, 50]"
                       :total="totalNumber"></el-pagination>
        <!--分页模块end-->

        <!--新增/编辑弹框start--333s-->
        <el-dialog :title="dialogAddOrEditName"
                   :visible.sync="dialogAddOrEdit"
                   width="50%"
                   :before-close="hideDialogAddOrEdit"
                   :close-on-click-modal="false"
                   >
            <template slot="title">
                <div class="avue-crud__dialog__header">
                    <span class="el-dialog__title">
                    <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                    {{dialogAddOrEditName}}
                    </span>
                </div>
            </template>
            <el-card>
            <el-form :model="formData"  :rules="rules"  ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="名称："  prop="topcategoryname">
                    <el-input v-model="formData.topcategoryname"></el-input>
                </el-form-item>
                <el-form-item label="序号：" prop="topcategorysort">
                    <el-input v-model="formData.topcategorysort" type="number" :min="1"></el-input>
                </el-form-item>
                <el-form-item >
                    <el-upload class="upload-demo"
                               :action="uploadUrl"
                               :on-change="handleChange"
                               multiple
                               :on-success="handleSuccess"
                               :before-remove="beforeRemove"
                               :on-exceed="handleExceed"
                               :file-list="uploadData">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <span style="color:#e6a23c;font-size:12px ">（只能上传jpg/png文件）</span>
                    </el-upload>
                </el-form-item>

            </el-form>
            </el-card>
            <span slot="footer"  class="dialog-footer">
                <el-button @click="dialogAddOrEdit = false">取 消</el-button>
                <el-button type="primary" :loading="formLoading"  @click="formSumbit">提交</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>

    // 新一级分类列表增删改查
    import {
        getCommodityCategory,
        addOrUpdateCommodityCategory,
        deleteCategory
    } from "../../api/classification/classification.js";
    import { BASE_URL } from "../../config/app";
    /*用作表单的数据初始化*/
    const formJson = {
        topcategoryname: null, // varchar(50) character set utf8 comment '分类名称',
        topcategorysort: null, // smallint(6) default NULL comment '排序字段',
        topcategorypic: null, // varchar(300) character set utf8 comment '封面图',
        level: 1,
    };

    export default {
        components: {},
        data() {
            return {
                uploadUrl: BASE_URL + '/goldendays-currency/tool/uploadpro', //上传图片
                uploadData: [],
                query: {
                    currentPage: 1,
                    level: 1,
                    pageSize: 5
                },
                formName: null,
                formMap: {
                    add: "添加",
                    edit: "一级分类编辑"
                },

                list: [], //列表集合
                totalNumber: 0, //分页总页数
                loading: true, //列表加载
                formLoading: false, //表单提交加载
                cancelToggle: false, //列表是否全选
                multipleSelection: [], //多选集合
                dialogAddOrEdit: false, //新增或编辑弹框开关
                dialogAddOrEditName: "", //新增或编辑弹框名字
                formData: formJson, //新增或修改的对象
                rules: {
                    //表单校验
                    topcategoryname: {
                        required: true,
                        message: "请输入分类名称",
                        trigger: "blur"
                    },

                    topcategorysort: {
                        required: true,
                        message: "请输入排序",
                        trigger: "blur"
                    }
                }
            };
        },

        methods: {
            /*获取列表事件*/
            getList() {
                this.loading = true;
                getCommodityCategory(this.query)
                    .then(response => {
                        if (response.code != 0) {
                            this.loading = false;
                            this.$message.error(response.message);
                            return false;
                        }
                        this.list = response.data.list || [];
                        this.totalNumber = response.data.totalNumber || 0;
                        setTimeout(() => {
                            this.loading = false;
                        }, 0.3 * 1000);
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                    });
            },
            // 上传前
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },

            // handleExceed
            handleExceed(files, fileList) {
                this.$message.warning(
                    `当前限制选择 1 个文件，如果换图请先删掉元原上传的图片后在操作！`
                );
            },

            //上传图片
            handleSuccess(response, file) {
                console.log(file);
                this.isSelect = false;
                console.log("上传成功");
                if (response.status === 1) {
                    const filePath = response.data;
                    this.formData.topcategorypic = filePath;
                    console.info(filePath + file);
                    //  alert(JSON.stringify(this.uploadData));
                    return;
                }

                this.$message.error("上传文件报错");
            },
            handleChange(file, fileList) {
                console.log(file);
                this.uploadData = [fileList[fileList.length - 1]]; // 覆盖
                this.fileName = file.name ? file.name : "";
                return false;
                // if (file.size > 1024 * 500) {
                //     fileList.pop();
                //     this.$message({
                //         message: "单个文件不超过20M!",
                //         type: "error"
                //     });
                // } else {
                //     this.uploadData = [fileList[fileList.length - 1]]; // 覆盖
                //     this.fileName = file.name ? file.name : "";
                //     // this.file = file.raw;
                // }
            },

            /*新增或者编辑提交事件*/
            formSumbit() {
                //表单校验通过
                this.$refs["ruleForm"].validate(valid => {
                    // console.log(valid)
                    if (valid) {
                        this.formData.topcategorysort = Number(
                            this.formData.topcategorysort
                        );
                        if(this.formData.topcategorysort<1){
                            this.$message.warning("输入序号值必须大于等于1")
                            return
                        }
                        addOrUpdateCommodityCategory(this.formData)
                            .then(response => {
                                this.formLoading = false;
                                if (response.code != 0) {
                                    this.$message.error(response.message);
                                    return false;
                                }
                                this.$message.success("操作成功");
                                this.hideDialogAddOrEdit();
                                // 加载表格数据
                                this.getList();
                                // 清空表单
                                this.$refs["dataForm"].resetFields();
                            })
                            .catch(() => {
                                this.formLoading = false;
                            });
                    }
                });
                //new URLSearchParams(this.query)  提交数据格式不正确时可以转一下
            },

            /*列表查询条件事件*/
            onSubmit() {
                this.query.currentPage = 1;
                this.getList();
            },

            /*刷新*/
            onRest() {
                //刷新事件需要重置查询条件
                this.query = {
                    currentPage: 1,
                    level: 1,
                    pageSize: 10
                };
                this.getList();
            },

            //显示 查看弹框
            detailForm(index, row) {
                if (row !== null) {
                    console.info(row);
                    this.uploadData = [];
                    this.dialogAddOrEdit = true;
                    this.formData = Object.assign({}, row);
                    let data = {
                        name: "",
                        url: ""
                    };
                    if (row.topcategorypic) {
                        let nameurl = row.topcategorypic;
                        data.url = nameurl;
                        data.name = nameurl.substring(nameurl.lastIndexOf("/") + 1);
                        this.uploadData.push(data);
                    }

                    this.dialogAddOrEditName = "一级分类编辑";
                }
            },

            /*显示 -新增或者编辑弹框*/
            showDialogAddOrEdit(index, row) {
                this.dialogAddOrEdit = true;
                if (row !== null) {
                    //如果row不为空，说明是修改，因为row是修改时携带过来此列的所有信息
                    this.formData = Object.assign({}, row); //修改则将列内容深拷贝到表单内容中
                    this.dialogAddOrEditName = "一级分类编辑";
                } else {
                    this.formData = Object.assign({}, formJson); //将弹框内表单内容初始化
                    this.uploadData = [];
                    this.dialogAddOrEditName = "添加";
                }
            },

            /*隐藏 -新增或编辑弹框*/
            hideDialogAddOrEdit() {
                this.dialogAddOrEdit = false;
                this.uploadData = [];
                //隐藏弹框时需要清除弹框内容
                if (this.$refs["ruleForm"]) {
                    this.$refs["ruleForm"].resetFields(); //清除formData表单
                    this.$refs["ruleForm"].clearValidate(); //清除表单验证
                }
                //如果上传文件，还需要清除文件列表
            },

            /*点击页数*/
            handleCurrentChange(val) {
                this.query.currentPage = val;
                this.getList();
            },

            /*选择每页条数【10,20,30,40,50】*/
            handleSizeChange(val) {
                this.query.pageSize = val;
                this.getList();
            },

            /*取消全选事件*/
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },

            /*列表复选框选择事件*/
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val == "") {
                    this.cancelToggle = false;
                    return;
                }
                this.cancelToggle = true;
            },

            /*全选删除事件*/
            delGroup() {
                console.log(this.multipleSelection);
                var ids = this.multipleSelection
                    .map(item => item.topcategoryid)
                    .join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({
                        message: "请先选择",
                        type: "warning"
                    });
                    return;
                }
                this.handleDel(ids);
            },

            /*单击删除事件*/
            handleDel(ids) {
                if (ids) {
                    this.$confirm("确认要删除吗?", "提示", {
                        type: "warning"
                    })
                        .then(() => {
                            let data= {
                                categoryid:ids,
                                type:1 //1级 2二级 3级
                            }
                            deleteCategory(data)
                                .then(response => {
                                    this.loading = false;
                                    if (response.code) {
                                        this.$message.error(response.message);
                                        return false;
                                    }
                                    this.$message.success("删除成功");
                                    // 刷新数据
                                    //this.list.splice(index, 1);
                                    this.getList();
                                })
                                .catch(() => {
                                    this.loading = false;
                                });
                        })
                        .catch(() => {
                            this.$message.warning("已取消");
                        });
                }
            },
            // 去关联商品属性模板页面
            toRelateTemplatePage(id,attributesid) {
                this.$router.push({
                    name: '关联商品属性模板',
                    path: "/commodity/relationAttributeTemplate", // 关联商家模板页面
                    query: {
                        id:id,
                        attributesid:attributesid,
                        from:'comeRelation'
                    }
                });
            }
        },
        created() {
            this.getList();
        }
    };
</script>
